<template>
  <div id="app">
    <template v-if="$route.path === '/login'">
      <router-view></router-view>
    </template>
    <template v-else>
      <el-container v-if="isRoutesLoaded">
        <el-header>
          <div class="header-content">
            <div class="logo">
              <h2>学生与班级后台管理系统</h2>
            </div>
            <div class="user-info">
              <i class="el-icon-user"></i>
              <span>{{ currentUser && currentUser.userName ? currentUser.userName : '管理员' }}</span>
              <span class="role-tag">{{ roleText }}</span>
              <el-button type="text" @click="handleLogout" class="logout-btn">
                <i class="el-icon-d-arrow-right"></i> 注销账号
              </el-button>
              <el-button type="text" @click="handleQuit" class="logout-btn">
                <i class="el-icon-switch-button"></i> 退出
              </el-button>
            </div>
          </div>
        </el-header>
        <el-container>
          <!--侧边栏-->
          <el-aside :width="isCollapse ? '64px' : '200px'">
            <div class="collapse-control">
              <i :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'" @click="isCollapse = !isCollapse"></i>
            </div>
            <el-menu 
              :default-active="activeIndex" 
              class="el-menu-vertical-demo" 
              @select="handleSelect"
              :collapse="isCollapse"
              router>
              <template v-for="menu in permissionMenus">
                <el-submenu v-if="menu && menu.children && menu.children.length > 0" :index="menu.path" :key="menu.path">
                  <template slot="title">
                    <i :class="menu.icon"></i>
                    <span>{{ menu.title }}</span>
                  </template>
                  <el-menu-item v-for="child in menu.children" :key="child.path" :index="child.path">
                    <i :class="child.icon"></i>
                    <span slot="title">{{ child.title }}</span>
                  </el-menu-item>
                </el-submenu>
                <el-menu-item v-else-if="menu" :index="menu.path" :key="menu.path">
                  <i :class="menu.icon"></i>
                  <span slot="title">{{ menu.title }}</span>
                </el-menu-item>
              </template>
            </el-menu>
          </el-aside>
          <!--内容-->
          <el-main>
            <router-view></router-view>
          </el-main>
        </el-container>
      </el-container>
      <div v-else class="loading-container">
        <el-card class="loading-card">
          <div slot="header">
            <span>系统加载中</span>
          </div>
          <el-progress :percentage="80" :indeterminate="true"></el-progress>
          <div class="loading-text">正在加载菜单和路由，请稍候...</div>
        </el-card>
      </div>
    </template>
  </div>
</template>

<script>

import { mapState, mapActions } from 'vuex';

export default {
  name: 'App',
  data() {
    return {
      activeIndex: '/statistics',
      isCollapse: false,
      currentUser: {
        userName: '',
        role: 0,
        id: null
      },
      roleMap: {
        0: '管理员',
        1: '教师',
        2: '学生'
      },
    }
  },
  computed: {
    ...mapState('permission', [
      'menuList',
      'isRoutesLoaded'
    ]),
    permissionMenus() {
      // 直接返回menuList，不再提供默认菜单
      return this.menuList || [];
    },
    roleText() {
      return this.currentUser && this.roleMap[this.currentUser.role] ? this.roleMap[this.currentUser.role] : '未知角色';
    },
    isRoutesLoaded() {
      return this.$store.state.permission.isRoutesLoaded;
    }
  },
  methods: {
    ...mapActions('permission', [
      'generateRoutes',
      'resetRoutes'
    ]),
    handleSelect(key) {
      this.activeIndex = key;
    },
    // 获取当前用户信息和权限菜单
    async fetchUserPermissions() {
      try {
        // 从localStorage获取用户信息
        const userInfoStr = localStorage.getItem('currentUser');
        if (!userInfoStr) {
          // 避免重复导航
          if (this.$route.path !== '/login') {
            this.$router.push('/login');
          }
          return Promise.reject('用户未登录');
        }
        
        // 解析用户信息
        try {
          this.currentUser = JSON.parse(userInfoStr) || {userName: '', role: 0, id: null};
        } catch (e) {
          console.error('解析用户信息失败', e);
          this.currentUser = {userName: '', role: 0, id: null};
          // 避免重复导航
          if (this.$route.path !== '/login') {
            this.$router.push('/login');
          }
          return Promise.reject('用户信息解析失败');
        }
        
        // 通过Vuex加载动态路由 - 这一步已经在vuex action中添加了路由，不需要再手动添加
        try {
          // 请求获取最新的菜单数据
          const role = this.currentUser.role;
          const menuResponse = await this.$http.get(`/menu/list/${role}`);
          let menuData = [];
          
          if (menuResponse.data && menuResponse.data.code === 200) {
            menuData = menuResponse.data.data || [];
            console.log('从后端获取的菜单数据:', menuData);
            // 保存到localStorage
            localStorage.setItem('permissionMenus', JSON.stringify(menuData));
          } else {
            console.warn('从后端获取菜单失败，尝试使用本地存储');
            // 尝试从localStorage获取菜单
            const menuString = localStorage.getItem('permissionMenus');
            if (menuString) {
              try {
                menuData = JSON.parse(menuString);
              } catch (e) {
                console.error('解析本地菜单数据失败', e);
                menuData = [];
              }
            }
          }
          
          // 使用Vuex生成动态路由，内部会自动添加路由
          const routes = await this.generateRoutes(menuData);
          
          // 如果当前是根路径，重定向到第一个可用的菜单
          this.redirectToAvailableRoute();
          
          return Promise.resolve(routes);
        } catch (error) {
          console.error('加载动态路由失败:', error);
          this.$message.error('加载菜单失败，请重新登录');
          
          // 导航到登录页
          if (this.$route.path !== '/login') {
            this.$router.push('/login');
          }
          
          return Promise.reject(error);
        }
      } catch (error) {
        console.error('获取权限菜单出错:', error);
        this.$message.error('获取权限菜单出错，请重新登录');
        
        // 导航到登录页
        if (this.$route.path !== '/login') {
          this.$router.push('/login');
        }
        
        return Promise.reject('获取菜单出错');
      }
    },
    
    // 重定向到可用路由
    redirectToAvailableRoute() {
      // 如果有权限菜单，重定向到第一个菜单项
      if (this.permissionMenus.length > 0) {
        const firstMenu = this.findFirstAvailableMenu(this.permissionMenus);
        if (firstMenu && firstMenu.path) {
          if (this.$route.path === '/') {
            this.$router.push(firstMenu.path).catch(err => {
              console.warn('导航到第一个可用菜单失败', err);
            });
          }
        } else {
          console.warn('没有找到可用的菜单项');
        }
      } else {
        console.warn('没有可用的菜单权限，无法重定向');
        // 如果没有菜单数据但用户已登录，默认导航到统计页
        if (localStorage.getItem('isLoggedIn') === 'true') {
          this.$router.push('/statistics').catch(err => {
            console.warn('导航到默认页面失败', err);
          });
        }
      }
    },
    
    // 找到第一个可用的菜单项
    findFirstAvailableMenu(menus) {
      if (!menus || menus.length === 0) return null;
      
      // 寻找第一个非隐藏的菜单
      for (const menu of menus) {
        if (menu && !menu.isHidden) {
          if (menu.children && menu.children.length > 0) {
            // 如果有子菜单，递归查找第一个可用的子菜单
            const firstChild = this.findFirstAvailableMenu(menu.children);
            if (firstChild) return firstChild;
          }
          return menu;
        }
      }
      
      return null;
    },
    
    // 处理退出登录
    handleLogout() {
      this.$confirm('确定注销账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('currentUser');
        localStorage.removeItem('jwt_token');
        // 重置路由
        this.resetRoutes();
        
        this.$message.success('注销成功');
        this.$router.push('/login');
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 处理退出系统
    handleQuit() {
      this.$confirm('确定退出系统?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('currentUser');
        localStorage.removeItem('jwt_token');

        // 重置路由
        this.resetRoutes();

        this.$message.success('退出成功');
        this.$router.push('/login');
      }).catch(() => {
        // 取消操作
      });
    }
  },
  created() {
    // 如果已登录且非登录页，获取用户权限
    if (localStorage.getItem('isLoggedIn') === 'true' && this.$route.path !== '/login') {
      this.fetchUserPermissions();
    }
  },
  watch: {
    // 监听路由变化，处理路由切换
    $route(to, from) {
      if (to.path !== '/login' && from.path === '/login') {
        // 从登录页导航到其他页面时，获取用户权限
        this.fetchUserPermissions();
      }
    }
  }
}
</script>

<style>
/* 全局样式 */
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}

#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.loading-card {
  width: 400px;
  text-align: center;
}

.loading-text {
  margin-top: 20px;
  color: #909399;
}

.el-container {
  height: 100%;
}

.el-aside {
  background-color: #f5f7fa;
  transition: width 0.3s;
  overflow: hidden;
}

.el-header {
  background-color: #409EFF;
  color: white;
  padding: 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info i {
  margin-right: 8px;
  font-size: 20px;
}

.role-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  margin-left: 8px;
}

.logout-btn {
  color: white;
  margin-left: 15px;
}

.el-menu {
  border-right: none;
}

.el-main {
  padding: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: calc(100% - 20px); /* 减去padding的高度 */
}

.collapse-control {
  text-align: center;
  padding: 10px 0;
  color: #409EFF;
  font-size: 20px;
  cursor: pointer;
}

/* 让表格占满整个main区域 */
.el-table {
  flex: 1;
  min-height: 300px;
  height: calc(100% - 200px); /* 减去其他元素的高度，包括分页 */
}

/* 表格内容区自动调整高度 */
.el-table__body-wrapper {
  overflow: auto;
}

/* 分页区域样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
</style>